import { ref, reactive, onMounted, computed, defineEmits, watch, getCurrentInstance } from 'vue';
import useUserStore from '@/store/modules/user';
import ContextMenu from '@imengyu/vue3-context-menu';
import printJS from 'print-js';
import {
  ApiPersonalTop,
  ApiPerDelFile,
  ApiPerCancelCollection,
  ApiPerAddCollection,
  ApiPerUpdateName,
  ApiPerDownloadFile,
  ApiPertreeCopy,
  ApiPertreeMove,
  ApiPerFilesDistribute,
  ApiPerTreeNodeAll,
  apiOnlinePrint,
  ApiPerfileExpert,
  ApiPerAgainfileExpert
} from '@/api/personDoc/personDocApi';
import { ApiTempCommitEnterprise } from '@/api/personDoc/tempApi';

export default function docMixins(configs: any) {
  const { proxy } = getCurrentInstance() as any;
  const { pageType, requstApi } = configs;
  const route = useRoute();
  const userStore = useUserStore();
  const copyAndMoveArray = ref([]); //保存要复制移动的数组

  const copyAndMoveType = ref(''); //保存当前要复制移动类别

  const yuDistributeRefs: any = ref();
  /**文件树参数---------------start */
  const headNodeId = ref('');
  const treeLoading = ref(false);
  const treeDocumentRefs: any = ref();

  const multipleTable = ref(null);
  const managementList = ref([]);
  const defaultProps: any = {
    //树
    children: 'children',
    label: 'realName',
    isLeaf: 'leaf'
  };
  const currentId = ref(0);
  const expandedKeys = ref([]);
  watch(currentId, (newVal) => {
    // 设置树高亮部分
    if (newVal !== null && newVal !== undefined) {
      (treeDocumentRefs.value as any).setCurrentKey(newVal);
    } else {
      (treeDocumentRefs.value as any).setCurrentKey(null);
    }
  });

  const treeRequestParams = ref({
    sort: ['real_name  Asc', 'sort Asc', 'type Desc', 'create_time Desc']
  });
  const rightInfoArray = ref([]);
  const teamId = ref(null);
  const tableRowArray = ref([]); //选中的表格数据
  /**文件树参数---------------end */
  /**面包屑参数---------------start */
  const breadList = ref([]);
  const stratBreadList = ref([]);
  /**面包屑参数---------------end */
  /**搜索----start */
  const searchInfoObj = ref({}); //保存搜索出来单击了的数据,用于高亮这一行
  const searchTableDataClone = ref([]);
  /**搜索----end */
  /**表格分页---start */
  const isTableHeaderBtn = ref(false); //是否隐藏表格头
  const tableHeight = ref(0);
  const tableData = ref([]);
  const previewTableDataClone = ref([]);
  const tableRequestParams: any = ref({
    page: 0,
    size: 40,
    parentId: 0,
    pageCount: 1
  });
  const tableLoading = ref(false);
  const isTableTopMoreText = ref(false);
  // 使用 watch 监听 isTableTopMoreText 的变化
  watch(isTableTopMoreText, (newValue, oldValue) => {
    // console.log(`isTableTopMoreText 发生变化: 从 ${oldValue} 变为 ${newValue}`);
  });
  const toploadMorePage = ref(0);
  /**表格分页---end */
  const propsButtonObj: any = ref({});
  // 拖拽配置参数
  const resizeConf = reactive({
    width: 270, // 初始宽度
    widthRange: [200, 1500] // 宽度范围
  });

  // 模版中心
  const TempCenterRef = ref(null);

  // 详情
  const FileInfoRef = ref();
  // 人员
  const ColleaguesRef = ref();
  const SelectUserRef = ref();

  const treeNodeList = ref([]);
  // 复制移动
  const CopymoveTreeRef = ref();

  // 上传模版
  const TempPubilshRef = ref();
  const outside = ref(true); // 判断调用组件方法
  //标签
  const TagsInfoRef = ref();

  // 分享
  const EnjoyListRef = ref();
  const EnjoyNum = ref(1);

  const docBtnRefs = ref(null);

  //企业
  const EnterpriseDialogRef = ref(null);

  // AI总结
  const AiTextRef = ref(null);
  const isAIShow = ref(1);

  //创建文件夹参数
  const yuCreateFolderRef = ref();
  const docBtnRefsData = ref(null);
  //---------------------------------------------------------------------------------------------------------

  // 上传文件弹窗
  const uploadFileRef = ref(null);

  // 定义选中文件夹数据
  const treeFolderData = reactive({
    type: '',
    parentId: null
  });

  //const emits: any = defineEmits(['sortChanged']); //有需要可以打开

  /**create-upload-btn组件事件--------------start */
  // 创建上传按钮点击事件
  const createUploadBtnClick = (command: any) => {
    // 新建文件夹
    if (command == 'newFolder') {
      opendialogRename('craete');
    }
    if (command == 'fileDialog') {
      tirggerFileDialog();
    }
    if (command == 'folderDialog') {
      tirggerFolderDialog();
    }
    // 打开模版中心
    if (command == 'center') {
      // opantemp();
      TempCenterRef.value.openTempDialog('', tableRequestParams.value.parentId);
    }
    // 新建自定义文档打开模版中心
    if (command == 'word' || command == 'excel' || command == 'ppt' || command == 'formDocument') {
      TempCenterRef.value.openTempDialog(command, tableRequestParams.value.parentId);
    }
  };

  // 关闭模版中心
  const closeDocumentDialog = () => {};

  // 上传方法
  const tirggerFileDialog = () => {
    treeFolderData.parentId = tableRequestParams.value.parentId;
    treeFolderData.type = configs.uploadType;
    uploadFileRef.value?.triggerFile(treeFolderData);
  };
  // 上传文件夹
  const tirggerFolderDialog = () => {
    treeFolderData.parentId = tableRequestParams.value.parentId;
    treeFolderData.type = configs.uploadType;
    uploadFileRef.value?.triggerFolder(treeFolderData);
  };

  // 标题栏点击事件
  const pageTitleClick = () => {
    breadRouterClick(stratBreadList.value[0]);
  };
  /**create-upload-btn组件事件--------------end */
  // 搜索按钮点击事件
  const handleSelectSearch = async (val) => {
    console.log('🚀 ~ handleSelectSearch ~ val:', val);
    searchInfoObj.value = val;
    let oParam = {
      id: val.id,
      fileType: 'personal',
      sort: treeRequestParams.value.sort,
      size: tableRequestParams.value.size
    };
    ApiPerTreeNodeAll(oParam).then((res) => {
      // console.log('🚀 ~ ApiPerTreeNodeAll ~ res索按钮点击事件:', res);
      let superiorList = [...res.data.superior];
      superiorList.shift();

      expandedKeys.value = res.data.superior.map((item) => {
        return parseInt(item.id);
      });

      treeDocumentRefs.value.setCurrentKey(expandedKeys.value[expandedKeys.value.length - 1]); //设置选中状态

      /**设置右边表格数据 */
      if (res.data.list.page > 1) {
        //判断是否是第一页,顶部加载更多按钮就不显示
        isTableTopMoreText.value = true;
      } else {
        isTableTopMoreText.value = false;
      }

      if (res.data.page <= 0) {
        isTableTopMoreText.value = false; //不显示顶部加载更多
      }

      // console.log('🚀 ~ .then ~ isTableTopMoreText:索按钮点击事件', isTableTopMoreText.value);

      tableData.value = [];
      if (expandedKeys.value.length == 1) {
        breadList.value = [];
      } else {
        breadList.value = superiorList;
      }

      toploadMorePage.value = res.data.list.page - 1;
      tableRequestParams.value.page = res.data.list.page - 1;
      tableRequestParams.value.pageCount = res.data.list.page; //这里为什么这样写:因为初始在请求列表中判断了页数和总页数,页数要比总页数小才能发送请求
      tableRequestParams.value.parentId = expandedKeys.value[expandedKeys.value.length - 1];
      apiTreeFileSelectTreePage('refresh');
    });
  };
  const filterNode = (value: any, data: any) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
  };
  // 获取树
  const apiFilesTreeQuery = async () => {
    treeLoading.value = true;
    await requstApi
      .apiTreeFileSelectTree({
        parentId: headNodeId.value,
        nodeType: pageType == 'self' ? 'folder' : '',
        teamId: pageType == 'team' ? route.params.teamId : '',
        ...treeRequestParams.value
      })
      .then((res) => {
        headNodeId.value = res.data.id;
        managementList.value = res.data.children;
        teamId.value = res.data.teamId;
        stratBreadList.value = [];
        breadList.value = [];
        stratBreadList.value.push({
          id: res.data.id,
          label: res.data.realName
        });

        /***************************************** 刷新时表格数据丢失所以注释这段start(已经解决) */
        // // 刷新保留树节点处理--------start
        let StoExpandedKeys = sessionStorage.getItem('expandedKeys');
        let StoExpandedKeysArr = [];

        if (StoExpandedKeys) {
          StoExpandedKeysArr = JSON.parse(StoExpandedKeys); //接收到的所有的id

          handleSelectSearch(StoExpandedKeysArr[StoExpandedKeysArr.length - 1]); //拿到的值取最后一层的id放到搜索接口去查询
        } else {
          initializeTableRequest(res.data.id);
        }
        // 刷新保留树节点处理--------end
        /***************************************** 刷新时表格数据丢失所以注释这段end */

        // initializeTableRequest(res.data.id); //初始化表格数据

        propsButtonObj.value = {};
        treeLoading.value = false;
      })
      .catch((err) => {
        treeLoading.value = false;
      });
  };

  // 获取左侧文件树---懒加载
  const loadNode = async (node: any, resolve: any) => {
    propsButtonObj.value = node;
    if (node.level == 0) {
      return resolve(node.data);
    }
    treeLoading.value = true;

    await requstApi
      .apiTreeFileSelectTree({
        parentId: node.data.id,
        nodeType: pageType == 'self' ? 'folder' : '',
        ...treeRequestParams.value
      })
      .then((res) => {
        breadList.value = [];
        treeLoading.value = false;
        let childrenArr = res.data.children;

        getTreeNode(treeDocumentRefs.value.getNode(node.data.id));
        // this.SET_TABLE_DATA(res.obj.children);
        if (expandedKeys.value[expandedKeys.value.length - 1] == node.data.id) {
          //tableScrollToRow(multipleTable.value, searchInfoObj.value); //需要时放开
          expandedKeys.value = [0];
          sessionStorage.removeItem('expandedKeys');
        }
        return resolve(childrenArr);
      })
      .catch((err) => {
        treeLoading.value = false;
      });
  };
  // 初始化分页查询右边表格接口请求数据
  const initializeTableRequest = (id: any) => {
    tableData.value = [];
    tableRequestParams.value.page = 0;
    tableRequestParams.value.pageCount = 1;
    tableRequestParams.value.parentId = id;
    apiTreeFileSelectTreePage('refresh');
  };

  // 分页查询右边表格---底部加载更多
  const apiTreeFileSelectTreePage = (type: any) => {
    // console.log(tableRequestParams.value.parentId, 'treePage');
    if (tableRequestParams.value.page > tableRequestParams.value.pageCount - 1) {
      return false;
    }

    tableLoading.value = true;
    requstApi
      .apiTreeFileSelectTreePage({
        parentId: tableRequestParams.value.parentId,
        page: tableRequestParams.value.page,
        size: tableRequestParams.value.size,
        ...treeRequestParams.value
      })
      .then((res: any) => {
        // console.log('🚀 ~ .then ~ res底部加载更多:', res);
        if (type == 'refresh') {
          tableData.value = res.data.rows;
        } else {
          tableData.value = [...tableData.value, ...res.data.rows];
        }

        if (res.data.page <= 1) {
          isTableTopMoreText.value = false; //不显示顶部加载更多
        }

        previewTableDataClone.value = tableData.value; //拷贝了一份，用来还原取消排序时的表格数据
        tableRequestParams.value.page += 1;
        tableRequestParams.value.pageCount = res.data.pageSize;

        tableLoading.value = false;
      })
      .catch((err) => {
        tableLoading.value = false;
        // console.log(err);
      });
  };

  // 分页查询右边表格---顶部加载更多
  const TopLoadMoreClick = () => {
    if (toploadMorePage.value <= 0) {
      toploadMorePage.value = 0;
      // this.isTableTopMoreText = false//不显示顶部加载更多
      return;
    }
    toploadMorePage.value -= 1;
    tableLoading.value = true;
    requstApi
      .apiTreeFileSelectTreePage({
        parentId: tableRequestParams.value.parentId,
        page: toploadMorePage.value,
        size: tableRequestParams.value.size,
        ...treeRequestParams.value
      })
      .then((res) => {
        if (res.data.page <= 0) {
          isTableTopMoreText.value = false; //不显示顶部加载更多
        }

        if (toploadMorePage.value <= 0) {
          isTableTopMoreText.value = false; //不显示顶部加载更多
        }

        tableData.value = [...res.data.rows, ...tableData.value];
        previewTableDataClone.value = tableData.value; //拷贝了一份，用来还原取消排序时的表格数据
        tableRequestParams.value.pageCount = res.data.pageSize;
        tableLoading.value = false;
      })
      .catch((err) => {
        tableLoading.value = false;
        toploadMorePage.value += 1;

        // console.log(err);
      });
  };

  //面包屑导航栏
  const getTreeNode = (node: any) => {
    if (node && node.label) {
      let obj = {
        id: node.key,
        label: node.label
      };

      breadList.value.unshift(obj);
      treeDocumentRefs.value.setCurrentKey(breadList.value[breadList.value.length - 1]); //设置选中状态
      sessionStorage.setItem('expandedKeys', JSON.stringify(breadList.value));
      getTreeNode(node.parent); //递归
    }
  };
  // 单击树
  const elTreeNodeClick = (data: any, node: any) => {
    propsButtonObj.value = node;
    refreshNode(data.id);
    handleRowClick(data);
  };

  // 刷新某个树节点，重点！！！！
  const refreshNode = (key: any, type?: any) => {
    // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
    let node = treeDocumentRefs.value.getNode(key);
    //  设置未进行懒加载状态
    node.loaded = false;
    // 重新展开节点就会间接重新触发load达到刷新效果
    node.expand();
    // 刷新右边表格
    if (type != 'delete') {
      initializeTableRequest(key);
      isTableTopMoreText.value = false;
      toploadMorePage.value = 0;
    }
    //团队权限
    // this.setTeamRoleFunction(key);
  };

  //功能方法==========================================================

  /**打开创建文件夹和重名 */
  const opendialogRename = (type: any, item?: any) => {
    if (type.type != 'richText') {
      let _data = yuCreateFolderRef.value;
      _data.title = '创建文件夹';
      // console.log(yuCreateFolderRef,'data');
      //重命名
      if (type == 'rename') {
        _data.visibleDialog = true;
        // yuCreateFolderRef.value.getDetailInfo(item);
        _data.form = JSON.parse(JSON.stringify(item));
        _data.title = '重命名';
      }
      _data.visibleDialog = true;
    } else {
      // richText后缀表单富文本
      // let params = {
      //   name: docBtnRefsData.value.form.rename,
      //   type: 1, // 个人0 团队1
      //   treeNodeId: tableRowArray.value[0].id,
      //   id: tableRowArray.value[0].id
      // };
      // bpmnFromsApi.apiSysFormDocUpdate(JSON.stringify(params)).then((res) => {
      //   docBtnRefsData.value.dialogRename = false;
      //   refreshDatas("更新成功");
      // });
    }
    // console.log(type,"type",item,"item团队文件重命名")
  };

  /**确定事件-创建文件夹和重命名 */
  const realNameConfirmClick = (item: any) => {
    //重命名
    let params = null;
    if (item.id) {
      if (item.type != 'richText') {
        let oParam = {
          folderName: item.realName,
          id: item.id,
          parentId: item.parentId
        };

        //文件夹和文件

        treeLoading.value = true;
        ApiPerUpdateName(oParam)
          .then((res) => {
            if (res.code == 401) {
              proxy?.$modal.msgError(res.msg);
              return;
            }
            refreshDatas();
            proxy?.$modal.msgSuccess('修改成功');
          })
          .catch((err) => {
            treeLoading.value = false;
          });
      } else {
        //表单父文件
        // params = {
        //   name: item.realName,
        //   type: pageType == "self" ? 0 : 1, // 个人0 团队1
        //   treeNodeId: item.id,
        //   id: item.id
        // };
        // treeLoading.value = true;
        // bpmnFromsApi
        //   .apiSysFormDocUpdate(JSON.stringify(params))
        //   .then((res) => {
        //     refreshDatas();
        //     proxy.$modal.msgSuccess("修改成功");
        //   })
        //   .catch((err) => {
        //     treeLoading.value = false;
        //   });
      }
    } else {
      //创建
      if (pageType == 'self') {
        //个人
        params = {
          parentId: propsButtonObj.value.key || headNodeId.value,
          folderName: item.realName
        };
      }
      //  else if (pageType == 'team') {
      //   //团队
      //   params = {
      //     parentId: propsButtonObj.value.key || headNodeId.value,
      //     realName: item.realName,
      //     teamId: teamId.value
      //   };
      // } else {
      //   //企业
      //   params = {
      //     parentId: propsButtonObj.value.key || headNodeId.value,
      //     realName: item.realName,
      //     extend: 1
      //   };
      // }
      treeLoading.value = true;
      requstApi
        .apiFilesTreeAddFolder(params)
        .then((res) => {
          if (res.code == '401') {
            proxy.$modal.msgError(res.message);
            return;
          }
          if (res.code != '400') {
            refreshDatas();
          } else {
            proxy.$modal.msgError(res.message);
          }
        })
        .catch((err) => {
          treeLoading.value = false;
        });
    }
  };
  /**table 方法和样式调整 ------------  start */
  //方法--------------------------
  // 当选择项发生变化时会触发该事件
  const handleSelectionChange = (selection: any) => {
    tableRowArray.value = selection;
    tableRowArray.value.length != 0 ? (isTableHeaderBtn.value = true) : (isTableHeaderBtn.value = false);
    //多个文件判断权限表格头按钮显示
    let paramsString = {};
    if (tableRowArray.value.length >= 1) {
      if (pageType == 'team') {
        paramsString = {
          teamId: teamId.value,
          userId: userStore.userId,
          treeNodeIds: tableRowArray.value.map((item) => item.id)
        };
        // this.$store.dispatch("getUserTeamFileRoleApi", {
        //   params: paramsString
        // });
      }
      if (pageType == 'enterprise') {
        // console.log(this.tableRowArray.find(item=>item.perm=='query',123))
        let paramsQuery = tableRowArray.value.find((item) => item.perm == 'query');
        let paramsEditor = tableRowArray.value.find((item) => item.perm == 'editor');
        if (paramsQuery) {
          // this.$store.dispatch("getEnteroriseFileRole", {
          //   params: paramsQuery
          // });
        } else if (paramsEditor) {
          // this.$store.dispatch("getEnteroriseFileRole", {
          //   params: paramsEditor
          // });
        } else {
          // this.$store.dispatch("getEnteroriseFileRole", {
          //   params: this.tableRowArray[0]
          // });
        }
      }
    }
  };

  // 双击表格的行(打开 and 预览)
  const handleRowDblClick = (val: any) => {
    // 展开左边树
    if (val.type == 'folder') {
      expandedKeys.value = [];
      refreshNode(val.id);
      currentId.value = val.id;
    }
    if (val.type == 'file') {
      // let routerObj = proxy?.$yuUtils.YUgetQueryParams(val);
      // console.log(routerObj, 'val');
      // console.log(44);

      // 跳转 -重定向跳转(文件预览)
      proxy.$yuUtils.previewSkipPage(val);
    }

    if (val.type == 'richText') {
      let params: any = {
        treeNodeId: val.id
      };

      // if (val.libraryType == 'enterprise') {
      //   params.type = 2; // 个人传0，团队传1 企业传2
      // } else if (val.libraryType == 'team') {
      //   params.type = 1;
      // }

      // this.getRichText(params);
    }
  };

  //打印
  const menuPrintClick = async (row) => {
    let params = {
      moduleId: row.id,
      type: 'personal'
    };
    let res = await apiOnlinePrint(params);
    const blobData = [res] as any[];
    const blob = new Blob(blobData, { type: 'application/pdf' });
    const blobURL = window.URL.createObjectURL(blob);
    printJS({
      type: 'pdf',
      printable: blobURL,
      documentTitle: '111', //标题
      targetStyle: '*',
      targetStyles: '*',
      scanStyles: true,
      // 默认800，设置1000是因为我窗口宽度是1000，而导致页面靠近左边，设置1000就正常居中了。
      maxWidth: '1300',
      // onPrintDialogClose:()=>{
      //     console.log(111111111111111);
      // },
      // onPdfOpen: ()=>{
      //   console.log(2222222222222222);
      // },

      //记录打印人员(暂无接口)
      onLoadingEnd: async () => {
        let params = {
          id: row.id,
          type: 'personal'
        };
        // let res = await collectionApi.apiOnlinePrintCallBack(params);
      }
      // onLoadingStart: function(){
      //   console.log(4444444444);
      // }
    } as any);
  };
  // 单击表格的行选中
  const handleRowClick = (val: any) => {
    rightInfoArray.value = val;
  };
  // 右键表格行
  const rowContextmenuClick = (row: any, column: any, event: any) => {
    multipleTable.value.clearSelection(); //清除选中
    multipleTable.value.toggleRowSelection(row); //设置选中行选中状态
    multipleTable.value.setCurrentRow(row); //用于单选表格，设定某一行为选中行
    onContextMenu(event, 'self');
  };
  // 排序(old舍弃)
  const changeTableS = (column: any, prop: any, order: any) => {
    let freeGood = [];
    let elseFree = [];
    let fieldName = column.prop;
    let sortingType = column.order === 'ascending' ? 'Asc' : column.order === 'descending' ? 'Desc' : null;

    if (fieldName === 'realName') {
      fieldName = 'real_name';
    }
    if (fieldName === 'updateTime') {
      fieldName = 'update_time';
    }
    if (sortingType === null) {
      fieldName = 'create_time';
      sortingType = 'Desc'; // 可以指定默认的排序方式，例如降序
    }

    tableData.value.forEach((item) => {
      if (item.sort == -1) {
        freeGood.push(item);
      } else {
        elseFree.push(item);
      }
    });

    // 根据排序类型进行排序
    if (sortingType === 'Desc' || sortingType === 'Asc') {
      elseFree.sort((a, b) => {
        if (typeof a[fieldName] === 'string') {
          return sortingType === 'Desc' ? b[fieldName].localeCompare(a[fieldName]) : a[fieldName].localeCompare(b[fieldName]);
        } else if (typeof a[fieldName] === 'number') {
          return sortingType === 'Desc' ? b[fieldName] - a[fieldName] : a[fieldName] - b[fieldName];
        }
      });
    }

    // 合并不参与排序的数据和排序后的数据
    tableData.value = [...freeGood, ...elseFree];

    // 更新 treeRequestParams.sort 数组的最后一个参数
    if (sortingType) {
      treeRequestParams.value.sort.pop(); // 移除最后一个元素
      treeRequestParams.value.sort.push(`${fieldName} ${sortingType}`);
    } else {
      // 如果没有排序方式，则还原排序参数
      treeRequestParams.value.sort = ['sort Asc', 'type Desc', 'update_time Asc'];
    }

    // console.log('🚀 ~ changeTableSort ~ treeRequestParams:', treeRequestParams.value.sort);

    // refreshDatas();
    //emits('sortChanged'); //有需要可以打开

    // 更新管理列表
    let folderData = tableData.value.filter((item) => item.type === 'folder');
    // console.log(folderData, "folderData");
  };

  //在用排序
  const changeTableSort = (column: any, prop: any, order: any) => {
    let freeGood = [];
    let elseFree = [];
    let fieldName = column.prop;
    let sortingType = column.order === 'ascending' ? 'Asc' : column.order === 'descending' ? 'Desc' : null;

    // 将字段名转换为数据库字段名
    if (fieldName === 'realName') {
      fieldName = 'real_name';
    }
    if (fieldName === 'updateTime') {
      fieldName = 'update_time';
    }

    // 记录列的点击次数
    if (!column.clickCount) {
      column.clickCount = 0; // 初始化点击次数
    }
    column.clickCount++;

    // 如果点击次数为3，恢复到默认排序
    if (column.clickCount === 3) {
      // 恢复默认排序
      column.clickCount = 0; // 重置点击次数
      sortingType = 'Desc'; // 默认降序
      fieldName = 'create_time'; // 默认按创建时间排序
    }

    // 将数据按是否可以排序分为两类
    tableData.value.forEach((item) => {
      if (item.sort == -1) {
        freeGood.push(item);
      } else {
        elseFree.push(item);
      }
    });

    // 根据排序类型进行排序
    if (sortingType === 'Desc' || sortingType === 'Asc') {
      elseFree.sort((a, b) => {
        if (typeof a[fieldName] === 'string') {
          return sortingType === 'Desc' ? b[fieldName].localeCompare(a[fieldName]) : a[fieldName].localeCompare(b[fieldName]);
        } else if (typeof a[fieldName] === 'number') {
          return sortingType === 'Desc' ? b[fieldName] - a[fieldName] : a[fieldName] - b[fieldName];
        }
        return 0;
      });
    }

    // 合并排序后的数据和不参与排序的数据
    tableData.value = [...freeGood, ...elseFree];

    // 更新 treeRequestParams.sort 数组，仅保留当前的排序字段
    if (sortingType) {
      // 清空现有的排序字段，只保留当前排序字段
      treeRequestParams.value.sort = [`${fieldName} ${sortingType}`];
    } else {
      // 如果没有排序方式，则恢复默认排序
      treeRequestParams.value.sort = ['real_name  Asc', 'sort Asc', 'type Desc', 'update_time Asc'];
    }

    // 判断是否为 size 排序，如果不是，则调用 refreshDatas()刷新数据
    if (fieldName !== 'size') {
      refreshDatas();
    }
    // emits('sortChanged'); //有需要可以打开

    // 更新管理列表
    let folderData = tableData.value.filter((item) => item.type === 'folder');
    // console.log(folderData, "folderData");
  };

  //样式调整------------------------
  // 单元格的 style 的回调方法
  const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 1) {
      return `borderColor:#eee;`;
    } else {
      return `border-right:0px`;
    }
  };

  // 合并第一行
  const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (rowIndex === 0) {
      return {
        rowspan: 1,
        colspan: 5 // 合并全部五列
      };
    }
  };
  //某一行改变背景色
  const tableRowClassName = ({ row, rowIndex }) => {
    if (row.sort == -1) {
      return 'table_row_topmark';
    }
  };
  //排序按钮显示方法
  const isTableHeaderBtnFunction = () => {
    if (tableRowArray.value.length == 0) {
      return 'custom';
    } else {
      return false;
    }
  };

  /**
   *  el-table滚动到表格某一行
   *  @param {object} tableElement  表格元素(this.$refs['表格ref值'])
   *  @param {Object} row   要定位的某一行数据
   * 调用实例   tableScrollToRow(this.$refs.editTable, {})
   */
  const tableScrollToRow = (tableElement: any, row: any) => {
    let rowIndex = tableData.value.findIndex((item) => item.id == row.id);
    let rowObj = tableData.value.find((item) => item.id == row.id);
    const theTableRows = tableElement.bodyWrapper.querySelectorAll('.el-table__body tbody .el-table__row');
    let scrollTop = 0;
    for (let i = 0; i < theTableRows.length; i++) {
      if (i === rowIndex) {
        break;
      }
      scrollTop += theTableRows[i].offsetHeight;
    }
    tableElement.bodyWrapper.scrollTop = scrollTop;
    tableElement.setCurrentRow(rowObj);
  };

  /**table 方法和样式调整 ------------  end */

  //点击文件获取详情信息--------------------
  const openFileDetailClick = async (row: any) => {
    await FileInfoRef.value.getDetailInfo(row);

    // console.log('🚀 ~ openFileDetailClick ~ row文件获取详情:', row);
  };

  //个人文档右边表格操作列的(更多)按钮 and 详情页面内右侧缩略图下的操作按钮------------------
  const moreHandleCommand = (command: any, item: any) => {
    console.log('🚀 ~ 更多系列:', command);
    // 预览/打开
    if (command == 'preview') {
      handleRowDblClick(item);
    }

    // 下载
    if (command == 'download') {
      downloadFileFunc([item]);
    }

    if (command == 'delete') {
      //删除
      deleteFileClick([item]);
    }

    if (command == 'rename') {
      // 重命名
      opendialogRename('rename', item);
    }

    if (command == 'move') {
      // 移动
      openDocumentTreeAll('move', [item]);
    }

    if (command == 'copy') {
      // 复制
      openDocumentTreeAll('copy', [item]);
    }

    if (command == 'outEnjoy') {
      // 分发
      openDistribute([item]);
    }
    //标签
    if (command == 'label') {
      openTagDialog([item]);
    }

    //编辑
    if (command == 'edit') {
      proxy?.$yuUtils.onlineEditSkipPage(item);
    }

    //个人模板库
    if (command == 'templateLibrary') {
      TempPubilshRef.value.personDialog(item);
    }

    //公共模板库
    if (command == 'publicTemplateLibrary') {
      TempPubilshRef.value.openPubilshDialog(item, outside.value);
    }

    // 提交到企业
    if (command == 'enterpriseLabel') {
      if (tableRowArray.value.length === 1) {
        EnterpriseDialogRef.value.openDialog([item]);
      } else {
        ElMessage.warning('请选择一个文件或文件夹进行操作');
      }
    }

    //专家知识库
    if (command == 'Expert') {
      submitExpert([item]);
    }
    //重新提交专家知识库
    if (command == 'ExpertAgain') {
      againExpert([item]);
    }
  };

  //导航栏
  const breadRouterClick = (val: any) => {
    if (breadList.value.length == 0) return;
    if (breadList.value[breadList.value.length - 1].id == val.id) return;
    if (val.id == headNodeId.value) {
      apiFilesTreeQuery();
      sessionStorage.removeItem('expandedKeys');
    } else {
      refreshNode(val.id);
    }
  };

  //table-header-btn $emit事件 (头部按钮)----------------
  const tableHeaderBtn_otherClick = (str: any) => {
    console.log('🚀 ~ 头部按钮 ~ str:', str);

    if (str == 'download') {
      // 下载
      downloadFileFunc(tableRowArray.value);
    }

    //删除
    if (str == 'delete') {
      deleteFileClick(tableRowArray.value);
    }

    //取消 or 收藏
    if (str == 'collection') {
      apiFilesCollectionAddCollection(tableRowArray.value[0]);
    }

    if (str == 'outEnjoy') {
      // 分发
      openDistribute(tableRowArray.value);
    }

    if (str == 'detail') {
      //详情或者版本
      if (tableRowArray.value.length != 1) {
        ElMessage.warning('暂不支持多个文件进行查看详情');
        return;
      }
      openFileDetailClick(tableRowArray.value[0]);
    }

    if (str == 'move') {
      // 移动
      openDocumentTreeAll('move', tableRowArray.value);
    }

    if (str == 'copy') {
      // 复制
      openDocumentTreeAll('copy', tableRowArray.value);
    }
    // 标签
    if (str == 'label') {
      openTagDialog(tableRowArray.value);
    }

    // 分享
    if (str == 'enjoy') {
      EnjoyListRef.value.openDialog(tableRowArray.value[0], EnjoyNum.value);
    }
    // 个人模版
    if (str == 'templateLibrary') {
      TempPubilshRef.value.personDialog(tableRowArray.value[0]);
    }

    //公共模板库
    if (str == 'publicTemplateLibrary') {
      TempPubilshRef.value.openPubilshDialog(tableRowArray.value[0], outside.value);
    }

    // 提交到企业
    if (str == 'enterpriseLabel') {
      if (tableRowArray.value.length === 1) {
        EnterpriseDialogRef.value.openDialog(tableRowArray.value[0]);
      } else {
        ElMessage.warning('请选择一个文件或文件夹进行操作');
      }
    }

    //AI总结
    if (str == 'AiSummary') {
      if (tableRowArray.value.length == 1) {
        AiTextRef.value.openFileDialog(tableRowArray.value, (isAIShow.value = 1));
      } else {
        ElMessage.warning('请选择一个文件进行操作');
      }
    }

    //AI翻译
    if (str == 'AiTranslate') {
      if (tableRowArray.value.length == 1) {
        AiTextRef.value.openFileDialog(tableRowArray.value, (isAIShow.value = 2));
      } else {
        ElMessage.warning('请选择一个文件进行操作');
      }
    }

    //AI摘要
    if (str == 'AiAbstract') {
      if (tableRowArray.value.length == 1) {
        AiTextRef.value.openFileDialog(tableRowArray.value, (isAIShow.value = 3));
      } else {
        ElMessage.warning('请选择一个文件进行操作');
      }
    }

    //AI抽取
    if (str == 'AiExtract') {
      if (tableRowArray.value.length == 1) {
        AiTextRef.value.openFileDialog(tableRowArray.value, (isAIShow.value = 4));
      } else {
        ElMessage.warning('请选择一个文件进行操作');
      }
    }

    // //AI问答 (取消了显示,但是代码还在(ai-text.vue))
    // if (str == 'AiQA') {
    //   if (tableRowArray.value.length == 1) {
    //     AiTextRef.value.openFileDialog(tableRowArray.value, (isAIShow.value = 5));
    //   } else {
    //     ElMessage.warning('请选择一个文件进行操作');
    //   }
    // }

    // 专家知识库
    if (str == 'Expert') {
      submitExpert(tableRowArray.value);
    }
    // 重新提交专家知识库
    if (str == 'AgainExpert') {
      againExpert(tableRowArray.value);
    }
  };

  //右键菜单(右击菜单显示按钮)-----------------------------------
  const onContextMenu = (e: any, type: any) => {
    setTimeout(() => {
      //这一步是解决菜单位置偏移的问题
      const element: any = document.querySelector('.mx-menu-host');

      if (element && element.style.top == '-12px') {
        element.classList.add('mx-menu-host_yu'); //这个样式在ruyi.scss中定义
      }
    }, 100);

    const scaledPosition = ContextMenu.transformMenuPosition(e.target as HTMLElement, e.offsetX, e.offsetY);
    // console.log(scaledPosition.y, scaledPosition.x, e.offsetX, '00000000');
    e.preventDefault();
    ContextMenu.showContextMenu({
      x: scaledPosition.x,
      y: scaledPosition.y,
      zIndex: 999,
      mouseScroll: true, //是否可以在菜单区域中使用鼠标滚轮来滚动长菜单
      // adjustPosition:true,//菜单将自动调整其位置，以防止溢出容器
      adjustPadding: { x: 0, y: 10 },
      customClass: 'ContextMenuClass', //自定义样式 在rouyi.scss中定义

      items: [
        {
          icon: 'icon-view iconfont-el',
          label: tableRowArray.value[0].type == 'folder' ? proxy.$t('teamDoc.rightBtnList.open') : proxy.$t('teamDoc.rightBtnList.preview'),
          // disabled: this.judgePermission("check", myFIleRoleList),
          onClick: () => {
            handleRowDblClick(tableRowArray.value[0]);
            // this.menuPreview();
          }
        },
        {
          icon: 'icon-edit iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.edit'),
          hidden: tableRowArray.value[0].type == 'folder',
          // disabled: this.judgePermission("update", myFIleRoleList),
          onClick: () => {
            // this.menuOnlineEdit();
            proxy?.$yuUtils.onlineEditSkipPage(tableRowArray.value[0]);
          }
        },
        // 打印
        {
          icon: 'icon-printer iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.print'),
          hidden:
            tableRowArray.value[0].type == 'folder' ||
            !(
              tableRowArray.value[0].suffix == 'doc' ||
              tableRowArray.value[0].suffix == 'docx' ||
              tableRowArray.value[0].suffix == 'xls' ||
              tableRowArray.value[0].suffix == 'xlsx' ||
              tableRowArray.value[0].suffix == 'pdf'
            ),
          // disabled: this.judgePermission("print", myFIleRoleList),
          onClick: () => {
            menuPrintClick(tableRowArray.value[0]);
          }
        },
        {
          icon: 'icon-downloads1 iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.download'),
          divided: true, //是否显示分割线
          // disabled: this.judgePermission("download", myFIleRoleList),
          onClick: () => {
            menuDownload();
          }
        },
        {
          icon: 'icon-top iconfont-el',
          label: tableRowArray.value[0].sort == -1 ? proxy.$t('teamDoc.rightBtnList.cancelTop') : proxy.$t('teamDoc.rightBtnList.top'),
          // disabled: this.judgePermission(pageType == "enterprise" ? "jurisdiction" : "update", myFIleRoleList),
          onClick: () => {
            TopMarkClick(tableRowArray.value[0]);
          }
        },
        {
          icon: 'icon-document-copy iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.copy'),
          // hidden: pageType == 'enterprise',
          // disabled: this.judgePermission("copy", myFIleRoleList),
          onClick: () => {
            openDocumentTreeAll('copy', tableRowArray.value);
            // this.menuCopy();
          }
        },
        {
          icon: 'icon-scissors iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.move'),
          // hidden: pageType == 'enterprise',
          // disabled: this.judgePermission("move", myFIleRoleList),
          onClick: () => {
            openDocumentTreeAll('move', tableRowArray.value);
            // this.menuMove();
          }
        },
        {
          icon: 'icon-delete iconfont-el',
          label: pageType != 'enterprise' ? proxy.$t('teamDoc.rightBtnList.delete') : proxy.$t('teamDoc.rightBtnList.invalid'),
          // disabled: this.judgePermission("delete", myFIleRoleList),
          onClick: () => {
            menuDelete();
          }
        },
        // {
        //   icon: 'icon-delete iconfont-el',
        //   label: proxy.$t('teamDoc.rightBtnList.deleteTemplate'),
        //   hidden: pageType == 'enterprise' && tableRowArray.value[0].hasOwnProperty('templateName') ? false : true,
        //   // disabled: this.judgePermission("delete", myFIleRoleList),
        //   onClick: () => {
        //     // this.delMod();
        //   }
        // },
        {
          icon: 'icon-key iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.rechristen'),
          divided: true, //是否显示分割线
          // disabled: this.judgePermission("update", myFIleRoleList),
          onClick: () => {
            menuRename();
          }
        },
        {
          icon: tableRowArray.value[0].collection == 0 ? 'iconfont icon-collect' : 'iconfont icon-collect-fill',
          label: tableRowArray.value[0].collection == 0 ? proxy.$t('teamDoc.rightBtnList.collect') : proxy.$t('teamDoc.rightBtnList.cancelCollect'),
          onClick: () => {
            // 收藏 or 取消收藏
            menuCollect();
          }
        },
        // {
        //   icon: tableRowArray.value[0].attention == 0 ? 'iconfont icon-like' : 'iconfont icon-like-fill',
        //   label:
        //     tableRowArray.value[0].attention == 0
        //       ? proxy.$t('teamDoc.rightBtnList.subscription')
        //       : proxy.$t('teamDoc.rightBtnList.cancelSubscription'),
        //   hidden: pageType == 'enterprise' || pageType == 'team' ? false : true,
        //   onClick: () => {
        //     // this.menuattention();
        //   }
        // },

        {
          icon: 'icon-collection iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.tags'),
          hidden: pageType != 'self',
          onClick: () => {
            openTagDialog(tableRowArray.value[0]);
            // this.menuLebal();
          }
        },

        {
          icon: 'icon-receiving iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.distribute'),
          // hidden: pageType == 'enterprise',
          // disabled: this.judgePermission("distribute", myFIleRoleList),
          onClick: () => {
            menuOutEnjoy();
          }
        },
        {
          icon: 'icon-share iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.share'),
          // hidden: pageType == 'enterprise',
          divided: true, //是否显示分割线
          // disabled: this.judgePermission("share", myFIleRoleList),
          onClick: () => {
            EnjoyListRef.value.openDialog(tableRowArray.value[0], EnjoyNum.value);
            // this.menuEnjoy(this.tableRowArray[0]);
          }
        },

        {
          icon: 'icon-wallet iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.details'),
          //divided: true, //是否显示分割线
          onClick: () => {
            openFileDetailClick(tableRowArray.value[0]);
          }
        },
        // {
        //   icon: 'icon-upload2 iconfont-el',
        //   label: '导出',
        //   hidden: tableRowArray.value[0].type != 'folder',
        //   divided: true, //是否显示分割线
        //   onClick: () => {
        //     // this.exportFun(this.tableRowArray[0]);
        //   }
        // },

        // {
        //   icon: 'icon-refresh iconfont-el',
        //   label: proxy.$t('teamDoc.rightBtnList.tbdzsk'),
        //   // hidden: this.isSyncKnowledgeFunc(this.tableRowArray),
        //   divided: true, //是否显示分割线
        //   onClick: () => {
        //     // this.synchronizationKnowledge(this.tableRowArray);
        //   }
        // },

        {
          icon: 'icon-more-outline iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.more'),
          customClass: 'ContextMenu_more_menu_btn',
          children: [
            {
              icon: 'icon-user iconfont-el',
              label: proxy.$t('teamDoc.rightBtnList.personalTemplateLibrary'),
              hidden: !(
                tableRowArray.value[0].type == 'file' &&
                ['ppt', 'pptx', 'excel', 'docx', 'doc', 'xlsx', 'xls', 'txt', 'pdf'].includes(tableRowArray.value[0].suffix)
              ),
              onClick: () => {
                TempPubilshRef.value.personDialog(tableRowArray.value[0]);
              }
            },

            {
              icon: 'icon-full-screen iconfont-el',
              label: proxy.$t('teamDoc.rightBtnList.commonTemplateLibrary'),
              hidden: !(
                tableRowArray.value[0].type == 'file' &&
                ['ppt', 'pptx', 'excel', 'docx', 'doc', 'xlsx', 'xls', 'txt', 'pdf'].includes(tableRowArray.value[0].suffix)
              ),
              onClick: () => {
                TempPubilshRef.value.openPubilshDialog(tableRowArray.value[0], outside.value);
              }
            },

            {
              icon: 'icon-plus iconfont-el',
              label: proxy.$t('teamDoc.rightBtnList.submitEnterprise'),
              hidden: pageType != 'team' && pageType != 'self', //是否隐藏菜单项
              // disabled: this.judgePermission("commitEnterprise", myFIleRoleList),
              onClick: () => {
                EnterpriseDialogRef.value.openDialog(tableRowArray.value);
                // this.menuEnterRoom();
              }
            },

            // 重新提交专家知识库
            {
              icon: 'icon-upload2 iconfont-el',
              label: '重新提交专家知识库',
              divided: false, //是否显示分割线
              hidden: !(
                (tableRowArray.value[0].expert == 'true' &&
                  tableRowArray.value[0].type == 'file' &&
                  ['csv', 'md', 'html', 'docx', 'xlsx', 'xls', 'txt', 'pdf', 'markdown', 'htm'].includes(tableRowArray.value[0].suffix)) ||
                (tableRowArray.value[0].type == 'folder' && tableRowArray.value[0].expert == 'true')
              ),
              onClick: () => {
                againExpert(tableRowArray.value[0]);
              }
            },

            // 专家知识库
            {
              icon: 'icon-upload2 iconfont-el',
              label: '专家知识库',
              hidden: !(
                (tableRowArray.value[0].expert != 'true' &&
                  tableRowArray.value[0].type == 'file' &&
                  ['csv', 'md', 'html', 'docx', 'xlsx', 'xls', 'txt', 'pdf', 'markdown', 'htm'].includes(tableRowArray.value[0].suffix)) ||
                (tableRowArray.value[0].type == 'folder' && tableRowArray.value[0].expert != 'true')
              ),

              onClick: () => {
                submitExpert(tableRowArray.value[0]);

                // this.menuEnterRoom();
              }
            }
          ]
        }

        // {
        //   icon: 'icon-more-outline iconfont-el',
        //   label: proxy.$t('teamDoc.rightBtnList.more'),
        //   customClass: 'ContextMenu_more_menu_btn',
        //   children: [
        //     {
        //       icon: 'icon-plus iconfont-el',
        //       label: proxy.$t('teamDoc.rightBtnList.commitTeam'),
        //       hidden: pageType != 'self',
        //       onClick: () => {
        //         // this.fileSubmitToTeam(this.tableRowArray);
        //       }
        //     },
        //     // {
        //     //   icon: 'icon-plus iconfont-el',
        //     //   label: proxy.$t('teamDoc.rightBtnList.submitEnterprise'),
        //     //   hidden: pageType != 'team' && pageType != 'self', //是否隐藏菜单项
        //     //   // disabled: this.judgePermission("commitEnterprise", myFIleRoleList),
        //     //   onClick: () => {
        //     //     // this.menuEnterRoom();
        //     //   }
        //     // },
        //     // {
        //     //   icon: 'icon-upload2 iconfont-el',
        //     //   label: proxy.$t('teamDoc.rightBtnList.fileIntoStorage'),
        //     //   hidden:
        //     //     pageType == 'enterprise' && proxy.$yuUtils.LicenseInfoFunc('archives:list') && tableRowArray.value[0].type != 'folder' ? false : true,
        //     //   // disabled: this.judgePermission("toArchives", myFIleRoleList),
        //     //   onClick: () => {
        //     //     // this.menuPigeonhole();
        //     //   }
        //     // },

        //     {
        //       icon: 'icon-circle-plus-outline iconfont-el',
        //       label: proxy.$t('teamDoc.rightBtnList.joinTemplates'),
        //       hidden:
        //         !(tableRowArray.value[0].type == 'file' && ['ppt', 'excel', 'docx'].includes(tableRowArray.value[0].suffix)) ||
        //         pageType == 'enterprise',
        //       // disabled: this.judgePermission("distribute", myFIleRoleList),
        //       onClick: () => {},
        //       children: [
        //         {
        //           label: proxy.$t('teamDoc.rightBtnList.personalTemplateLibrary'),
        //           onClick: () => {
        //             // this.templateLibrary();
        //           }
        //         },
        //         {
        //           label: proxy.$t('teamDoc.rightBtnList.commonTemplateLibrary'),
        //           onClick: () => {
        //             // this.publicTemplateLibrary();
        //           }
        //         }
        //       ]
        //     },

        //     {
        //       icon: 'icon-reading iconfont-el',
        //       label: proxy.$t('teamDoc.rightBtnList.tagDocuments'),
        //       hidden: pageType != 'enterprise',
        //       // disabled: this.judgePermission("enterpriseLabel", myFIleRoleList),
        //       onClick: () => {
        //         // this.menuManyDimensions(this.tableRowArray[0]);
        //       }
        //     },
        //     {
        //       icon: 'icon-c-scale-to-original iconfont-el',
        //       label: proxy.$t('teamDoc.rightBtnList.fileWatermarking'),
        //       hidden: pageType != 'enterprise',
        //       // disabled: this.judgePermission("watermark", myFIleRoleList),
        //       onClick: () => {
        //         // this.OpenFileWatermark(this.tableRowArray[0]);
        //       }
        //     },
        //     {
        //       icon: 'icon-data-analysis iconfont-el',
        //       label:
        //         tableRowArray.value[0].toTms == 'true' ? proxy.$t('teamDoc.rightBtnList.canceTrain') : proxy.$t('teamDoc.rightBtnList.joinTrain'),
        //       // label: `加入培训资源${this.$store.state.settings.train_enable == 'true'}${pageType != "self"}${this.tableRowArray[0].type == "file"}`,
        //       // hidden: !(this.$store.state.settings.train_enable == "true" && pageType != "self" && this.tableRowArray[0].type == "file"),
        //       // disabled: this.judgePermission("jurisdiction", myFIleRoleList),
        //       onClick: () => {
        //         // this.addTrainResourceClick(this.tableRowArray[0]);
        //       }
        //     },
        //     {
        //       icon: 'icon-sort iconfont-el',
        //       label: proxy.$t('teamDoc.rightBtnList.inOut'),
        //       // hidden: this.fileFerryHidden(),
        //       onClick: () => {
        //         // this.FileFerryDocuments(this.tableRowArray);
        //       }
        //     },

        //     {
        //       icon: 'icon-link iconfont-el',
        //       label: proxy.$t('teamDoc.rightBtnList.inviteCollaboration'),
        //       hidden: pageType != 'self',
        //       onClick: () => {
        //         // this.menuInvitationEdit(this.tableRowArray[0]);
        //       }
        //     }
        //   ]
        // }
      ]
    });
  };
  /**其他方法-------------------------------------------- */

  /**刷新表格和数节点 刷新- 操作按钮之后刷新表格和树节点 */
  const refreshDatas = (str?: any) => {
    if (str) {
      proxy?.$modal.msgSuccess(str);
    }
    if (propsButtonObj.value.key) {
      refreshNode(propsButtonObj.value.key);
    } else {
      apiFilesTreeQuery();
    }
  };
  /**icon转换 */
  const selectSvgIcons = (v: any) => {
    return proxy.$yuUtils.selectSvgIcon(v);
  };
  /****************************************************方法start */
  // 下载
  const menuDownload = () => {
    downloadFileFunc(tableRowArray.value);
  };

  /**下载==================================================start */
  // 单个下载
  const downloadFileFunc = async (itemArr: any) => {
    // console.log('🚀 ~ downloadFileFunc ~ res:', item);
    let ids = itemArr.map((item: any) => item.id);
    proxy?.$download.downloadFile(ids, itemArr[0].libraryType);
    return;

    if (itemArr.type == 'richText') {
      ElMessage.warning('暂不支持下载.richText格式的文件');
      return;
    } else {
      // 判断item是否是数组，如果不是，则将其包装成数组
      const items = Array.isArray(itemArr) ? itemArr : [itemArr];

      let ids = items.map((item) => {
        return item.id.toString() || item.storageId.toString();
      });

      let oParam = {
        storageIds: ids,
        type: items[0].libraryType
      };

      ApiPerDownloadFile(oParam).then((res) => {
        if (res.code == 200) {
          proxy.$yuUtils.previewSkipPage(res);
          // console.log('🚀 ~ downloadFileFunc ~ res:', res);
        }
      });
    }
  };

  /**下载==================================================end */

  //提交专家知识库
  const submitExpert = async (val: any) => {
    // 检查 val 是否为数组，如果不是，则将其转换为数组
    if (!Array.isArray(val)) {
      val = [val]; // 如果 val 不是数组，则转换为数组
    }

    let oParam = {
      fileIds: val.map((item: any) => item.id),
      type: val[0].type
    };

    ApiPerfileExpert(oParam).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('提交成功 !');
        refreshDatas();
      }
    });
  };

  //重新提交专家知识库
  const againExpert = async (val: any) => {
    console.log('🚀 ~ againExpert ~ val:重新提交专家知识库', val);
    // 检查 val 是否为数组，如果不是，则将其转换为数组
    if (!Array.isArray(val)) {
      val = [val]; // 如果 val 不是数组，则转换为数组
    }

    let oParam = {
      fileIds: val.map((item: any) => item.id),
      type: val[0].type
    };

    ApiPerAgainfileExpert(oParam).then((res) => {
      console.log('🚀 ~ ApiPerAgainfileExpert ~ oParam:', oParam);
      if (res.code == 200) {
        proxy.$modal.msgSuccess('提交成功 !');
        refreshDatas();
      }
    });
  };

  // 调用删除
  const menuDelete = () => {
    deleteFileClick(tableRowArray.value);
  };

  // 删除方法
  const deleteFileClick = (val: any) => {
    ElMessageBox.confirm('将删除' + val.length + '条数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        let ids = val.map((item: any) => item.id);

        let oParam = {
          ids: ids.join(','),
          type: val[0].libraryType
        };

        ApiPerDelFile(oParam).then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('删除成功 !');
            refreshDatas();
            // apiFilesTreeQuery(); //刷新页面
          }
        });
      })
      .catch(() => {});
  };

  // 调用收藏 or 取消收藏
  const menuCollect = () => {
    apiFilesCollectionAddCollection(tableRowArray.value[0]);
  };

  // 收藏 or 取消收藏 方法
  const apiFilesCollectionAddCollection = (val: any) => {
    let fileType = 0;
    if (val.collection == '1') {
      let oParam = {
        treeNodeId: val.id,
        fileType: fileType
      };

      ApiPerCancelCollection(oParam).then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('取消收藏成功 !');
          val.collection = '0';
          refreshDatas();
          // apiFilesTreeQuery(); //刷新页面
        }
      });
    } else {
      let oParam = {
        treeNodeId: val.id,
        fileType: fileType
      };

      ApiPerAddCollection(oParam).then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('收藏成功了哦~');
          val.collection = '1';
          refreshDatas();
          // apiFilesTreeQuery(); //刷新页面
        }
      });
    }
  };

  // 重命名
  const menuRename = () => {
    opendialogRename('rename', tableRowArray.value[0]);
  };

  // 调用分发
  const menuOutEnjoy = () => {
    openDistribute(tableRowArray.value);
  };

  /*分发同事===========*/
  const openDistribute = (val) => {
    treeNodeList.value = val;
    SelectUserRef.value.openDialogTransfer();
  };

  // 分发对话框确定按钮
  const sureDialogTransferClick = (val) => {
    if (val.length == 0) {
      ElMessage.warning('请选择你要分发的同事');
      return;
    }
    let userIds = val.map((item) => {
      return item.userId;
    });

    let treeNodeIds = treeNodeList.value.map((item) => {
      return item.id;
    });

    let fileName = '';
    if (treeNodeList.value.length == 1) {
      fileName = treeNodeList.value[0].realName;
    } else {
      fileName = treeNodeList.value[0].realName + '等';
    }

    let oParam = {
      treeNodeId: treeNodeIds.join(','),
      type: '0',
      userIds: userIds,
      fileName: fileName
    };

    ApiPerFilesDistribute(oParam).then((res) => {
      ElMessage.success('操作成功');
      SelectUserRef.value.closeDialogTransferClick();
    });
  };

  // const debounce_sureDialogTransferClick = (val) => {
  //   if (val.length == 0) {
  //     ElMessage.warning('请选择你要分发的同事');
  //     return;
  //   }
  //   let userIds = val.map((item) => {
  //     return item.typeId;
  //   });

  //   let treeNodeIds = treeNodeList.value.map((item) => {
  //     return item.id;
  //   });

  //   let fileName = '';
  //   if (treeNodeList.value.length == 1) {
  //     fileName = treeNodeList.value[0].realName;
  //   } else {
  //     fileName = treeNodeList.value[0].realName + '等';
  //   }

  //   let oParam = {
  //     treeNodeId: treeNodeIds.join(','),
  //     type: '0',
  //     userIds: userIds,
  //     fileName: fileName
  //   };
  //   ApiPerFilesDistribute(oParam).then((res) => {
  //     ElMessage.success('操作成功');
  //     ColleaguesRef.value.TeamPersonList = [];
  //     ColleaguesRef.value.searchUserList = [];
  //     ColleaguesRef.value.dialogTransfer = false;
  //     // refreshDatas();
  //   });
  // };

  //复制复制and移动
  const openDocumentTreeAll = async (type, val) => {
    treeLoading.value = true;
    await CopymoveTreeRef.value.openDialog();
    treeLoading.value = false;
    copyAndMoveType.value = type; //保存当前要复制移动类别
    copyAndMoveArray.value = val;
    // console.log(type, '复制and移动');
    // console.log(val, '数据');
  };

  /**
   * 复制粘贴移动--树弹窗确定按钮
   * 注意:后端处理了:复制移动不能做复制到自己的子目录
   * */
  const sureClick = (val) => {
    let ids = copyAndMoveArray.value.map((item) => {
      return item.id;
    });
    if (copyAndMoveType.value == 'move') {
      if (copyAndMoveArray.value[0].parentId == val.id) {
        treeLoading.value = false;
        ElMessage.warning('目标目录是原文件当前目录');
        return;
      }
      let oParam = {
        ids: ids,
        parentId: val.id
      };
      ApiPertreeMove(oParam)
        .then((res) => {
          // console.log('🚀 ~ 移动 ~ res', res);

          refreshDatas();
          copyAndMoveType.value = '';
          copyAndMoveArray.value = [];
          if (res.code == 206) {
            ElMessage({
              message: res.msg,
              duration: 5000,
              type: 'warning',
              showClose: true
            });
          } else {
            ElMessage.success('操作成功');
          }
          treeLoading.value = false;
        })
        .catch((err) => {
          treeLoading.value = false;
        });
      // console.log('移动');
    } else {
      let oParam = {
        ids: ids,
        parentId: val.id
      };
      ApiPertreeCopy(oParam)
        .then((res) => {
          // console.log('🚀 ~ 复制 ~ res', res);

          refreshDatas();
          ElMessage.success('操作成功');
          copyAndMoveType.value = '';
          copyAndMoveArray.value = [];
          treeLoading.value = false;
        })
        .catch((err) => {
          treeLoading.value = false;
        });
      // console.log('复制');
    }
  };

  // 提交到企业
  const EntSureClick = (val) => {
    let oParam = {
      id: tableRowArray.value[0].id,
      enterpriseId: val.id
    };
    ApiTempCommitEnterprise(oParam).then((res) => {
      if (res.code == 200) {
        ElMessage.success('提交成功');
        refreshDatas();
      }
    });
  };

  /** 打开标签对话框 */
  const openTagDialog = (val) => {
    TagsInfoRef.value.openTagsDialog(val);
  };

  /**置顶 */
  const TopMarkClick = (val: any) => {
    let oParam = {
      ids: [val.id],
      top: val.sort == -1 ? false : true
    };
    ApiPersonalTop(oParam).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('设置成功 !');
        refreshDatas();
        // apiFilesTreeQuery(); //刷新页面
      }
    });
  };

  // 模版使用成功后调用
  const getAddDocument = () => {
    refreshDatas();
  };

  /****************************************************方法start */
  // 监听表格滚动

  onMounted(() => {
    apiFilesTreeQuery();
    tableHeight.value = window.innerHeight - 98;
    window.onresize = () => {
      //浏览器窗口变动的时候
      tableHeight.value = window.innerHeight - 98;
    };
  });

  onUnmounted(() => {
    // 在组件销毁时清除存储的 'expandedKeys' 数据
    sessionStorage.removeItem('expandedKeys');
  });

  return {
    AiTextRef,
    EntSureClick,
    EnterpriseDialogRef,
    getAddDocument,
    sureDialogTransferClick,
    SelectUserRef,
    EnjoyListRef,
    TempPubilshRef,
    TempCenterRef,
    closeDocumentDialog,
    TagsInfoRef,
    sureClick,
    CopymoveTreeRef,
    ColleaguesRef,
    FileInfoRef,
    yuDistributeRefs,
    resizeConf,
    headNodeId,
    propsButtonObj,
    managementList,
    defaultProps,
    treeDocumentRefs,
    currentId,
    expandedKeys,
    yuCreateFolderRef,
    tableLoading,
    isTableTopMoreText,
    tableData,
    tableHeight,
    tableRowArray,
    isTableHeaderBtn,
    stratBreadList,
    breadList,
    multipleTable,
    createUploadBtnClick,
    handleSelectSearch,
    pageTitleClick,
    loadNode,
    filterNode,
    elTreeNodeClick,
    opendialogRename,
    realNameConfirmClick,
    apiTreeFileSelectTreePage,
    TopLoadMoreClick,
    tableRowClassName,
    isTableHeaderBtnFunction,
    handleSelectionChange,
    handleRowDblClick,
    handleRowClick,
    rowContextmenuClick,
    changeTableSort,
    selectSvgIcons,
    openFileDetailClick,
    apiFilesCollectionAddCollection,
    moreHandleCommand,
    breadRouterClick,
    tableHeaderBtn_otherClick,
    onContextMenu,
    uploadFileRef,
    tirggerFileDialog,
    tirggerFolderDialog,
    refreshDatas
  };
}
